/* client.c */
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>  
#include <sys/wait.h>
#include <netinet/in.h>
#include <arpa/inet.h>


#define MAXLINE 80
#define SERV_PORT 9000

void
sig_handle (int signo) {
    pid_t   pid;
    int     stat;

    pid = wait(&stat);

    printf("Child Process %d Terminated\n", pid);

    return;
}

int
main (int argc, char *argv[]) {
    struct sockaddr_in servaddr;

    char buffer[MAXLINE];

    char input[MAXLINE];

    int socketfd, n;

    socketfd = socket(AF_INET, SOCK_STREAM, 0);

    bzero(&servaddr, sizeof(servaddr));

    servaddr.sin_family = AF_INET;

    inet_pton(AF_INET, "127.0.0.1", &servaddr.sin_addr);

    servaddr.sin_port = htons(SERV_PORT);

    connect(socketfd, (struct sockaddr *) &servaddr, sizeof(servaddr));

    // 处理子进程结束信号
    signal(SIGCHLD, sig_handle);

    // fgets从指定的流stream读取一行
    while (fgets(input, MAXLINE, stdin) != NULL) {
        printf("Send msg: %s", input);

        // 向服务端发送消息
        write(socketfd, input, strlen(input));

        // 开启子进程从服务端接收信息
        pid_t child = fork();

        if (child) {
            while (n = read(socketfd, buffer, MAXLINE) > 0) {
                printf("Received msg: %s", buffer);
            }
        }
    }

    close(socketfd);

    return 0;
}
